package com.test.realcityalfa.components;

import com.test.realcityalfa.R;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

public class ClearableEditText extends EditText{

	Drawable imgClearButton = getResources().getDrawable(R.drawable.clear_button);
	
	public ClearableEditText(Context context, AttributeSet attrs, int defStyle) 
	{
		super(context, attrs, defStyle);
		init();
	}

	public ClearableEditText(Context context, AttributeSet attrs) 
	{
		super(context, attrs);
		init();
	}
	
	public ClearableEditText(Context context) 
	{
		super(context);
		init();
	}
	
	private void init()
	{
		this.imgClearButton.setBounds(0, 0, imgClearButton.getIntrinsicWidth(), imgClearButton.getIntrinsicHeight());
		
		handleClearButton();
		
		this.setOnTouchListener(new OnTouchListener() 
		{
			@Override
			public boolean onTouch(View v, MotionEvent event) 
			{
			 
				ClearableEditText et = ClearableEditText.this;
					 
				if (et.getCompoundDrawables()[2] == null)
				return false;
					                 
				if (event.getAction() != MotionEvent.ACTION_UP)
				return false;
	
				if (event.getX() > et.getWidth() - et.getPaddingRight() - imgClearButton.getIntrinsicWidth()) 
				{
					et.setText("");
					ClearableEditText.this.handleClearButton();
				}
				return false;
			}
			
		});
				 
		//if text changes, take care of the button
		this.addTextChangedListener(new TextWatcher() 
		{
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {

			ClearableEditText.this.handleClearButton();
		}
				 
			@Override
			public void afterTextChanged(Editable arg0) {
			}
				 
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
		});
	}
	
	void handleClearButton() 
	{
		if (this.getText().toString().equals(""))
		{
			// add the clear button
			this.setCompoundDrawables(this.getCompoundDrawables()[0], this.getCompoundDrawables()[1], null, this.getCompoundDrawables()[3]);
		}
		else
		{
			//remove clear button
			this.setCompoundDrawables(this.getCompoundDrawables()[0], this.getCompoundDrawables()[1], imgClearButton, this.getCompoundDrawables()[3]);
		}
	}
}

